import { validatenull } from "./validate";
import html2canvas from 'html2canvas';

/**
 * 限制输入框为整数
 * @param value 输入的值
 */
export function limitNumber(value) {
  if (typeof value === "string") {
    return !isNaN(Number(value)) ? value.replace(/^(0+)|[^\d]/g, "") : "";
  } else if (typeof value === "number") {
    return !isNaN(value) ? String(value).replace(/^(0+)|[^\d]/g, "") : "";
  } else {
    return "";
  }
}

/**
 * 秒数转为 时:分:秒
 * @param time
 * @returns {string}
 */
export function formatTime(time) {
  let hours = Math.floor(time / 3600);
  let minute = Math.floor(Math.floor(time % 3600) / 60);
  let second = time % 60;
  hours = hours.toString().length === 1 ? `0${hours}` : hours;
  minute = minute.toString().length === 1 ? `0${minute}` : minute;
  second = second.toString().length === 1 ? `0${second}` : second;
  return hours + ":" + minute + ":" + second;
}

/**
 * 转换成星期
 * @param weekStr
 */
export function toWeek(weekStr) {
  if (validatenull(weekStr)) return "";
  let weekArr = weekStr.split(",");
  let result = "";
  if (weekArr.length === 7) {
    result = "全星期";
  } else {
    weekArr.forEach(item => {
      result +=
        item == "1"
          ? "周一 ,"
          : item == "2"
          ? "周二 ,"
          : item == "3"
          ? "周三 ,"
          : item == "4"
          ? "周四 ,"
          : item == "5"
          ? "周五 ,"
          : item == "6"
          ? "周六 ,"
          : "周日 ,";
    });
    result = result.substr(0, result.length - 1);
  }
  return result;
}
/**
 * 获取音视频时长
 * @param file
 */
export function getDuration(file) {
  let url = URL.createObjectURL(file);
  let audioElement = new Audio(url);
  let duration;
  return new Promise(resolve => {
    audioElement.addEventListener("loadedmetadata", async function() {
      duration = audioElement.duration; //时长为秒，小数，182.36
      //   this.$parent.$data.wDuration = parseInt(duration)
      resolve(formatTime(parseInt(duration)));
    });
  });
}
/**
 * 整理为树形数据
 * @param data 需要整理的数据
 */
 export function list2Tree(data) {
  let result = []
  if(!Array.isArray(data)) {
      return result
  }
  data.forEach(item => {
      item.children=[];
  });
  let map = {};
  data.forEach(item => {
      map[item.id] = item;
  });
  data.forEach(item => {
      let parent = map[item.pid];
      if(parent) {
          (parent.children || (parent.children = [])).push(item);
      } else {
          result.push(item);
      }
  });
  return result;
}

export function timeFix() {
  const timeList = ["早上好", "上午好", "中午好", "下午好", "晚上好"];
  const time = new Date();
  const hour = time.getHours();
  return hour < 9
    ? timeList[0]
    : hour <= 11
    ? timeList[1]
    : hour <= 13
    ? timeList[2]
    : hour <= 20
    ? timeList[3]
    : timeList[4];
}

/**
 * 整理成框架用的用户菜单数据
 * @param data 后端返回的菜单数据
 */
export function sortMenu(data) {
  let routesConfig = [];
  routesConfig.push({
    router: "root"
  });
  let children = [];
  for (let i in data) {
    children.push({
      router: data[i]["path"],
      children: []
    });
    for (let j in data[i]["children"]) {
      children[i]["children"].push(data[i]["children"][j]["path"]);
      //把二级菜单的子页面也插入二级路由同层,避免异步路由无法加载二级菜单子页面
      for (let m in data[i]["children"][j].children) {
        if (data[i]["children"][j]["children"][m]["type"] == "V") {
          children[i]["children"].push(
            data[i]["children"][j]["children"][m]["path"]
          );
        }
      }
    }
  }
  routesConfig[0]["children"] = children;
  return routesConfig;
}
/**
 * 整理成框架用的用户权限数据
 * @param data 后端返回的菜单数据
 */
export function sortPermission(data) {
  let permissionConfig = [];
  let index = 0;
  for (let i in data) {
    for (let j in data[i]["children"]) {
      permissionConfig.push({
        id: data[i]["children"][j]["perms"],
        operation: []
      });
      for (let m in data[i]["children"][j]["children"]) {
        permissionConfig[index]["operation"].push(
          data[i]["children"][j]["children"][m]["perms"]
        );
      }
      index++;
    }
  }
  return permissionConfig;
}

export function getObjName(arr, field) {
  let nameArr = [];
  for (let i in arr) {
    nameArr.push(arr[i][field]);
  }
  return nameArr.join(",");
}

/**
 * 获取多选名称
 * @param arr
 * @param filedName
 * @returns {string}
 */
export function getDataName(arr, filedName) {
  let names = "";
  arr.forEach(item => {
    names += item[filedName] + ",";
  });
  return names.substring(0, names.length - 1);
}

/**
 * html转canvas
 * @param el
 * @param options
 */
export function htmlToCanvas(el, options) {
  return new Promise((resolve)=>{
    html2canvas(el,options).then((canvas)=>{
      let context = canvas.getContext('2d');
      context.mozImageSmoothingEnabled = false;
      context.webkitImageSmoothingEnabled = false;
      context.msImageSmoothingEnabled = false;
      context.imageSmoothingEnabled = false;
      resolve(canvas);
    })
  })
}

/**
 * canvas转图片blob
 * @param canvas
 */
 export function canvasToImage(canvas) {
  let data = canvas.toDataURL('image/jpeg', 1);
  data = data.split(',')[1];
  data = window.atob(data);
  var ia = new Uint8Array(data.length);
  for (let i = 0; i < data.length; i++) {
    ia[i] = data.charCodeAt(i);
  }
  let blob = new Blob([ia], {
    type: 'image/jpeg',
  });
  return blob;
}

export function imgToBase64(imgUrl){
  let reader = new FileReader();
  let base64;
  if(imgUrl != undefined){
    reader.readAsDataURL(imgUrl);
    reader.onload = ( e )=>{
      let imgFile = e.target.result;
      let arr = imgFile.split(",");
      base64 = `data:image/png;base64,${arr[1]}`;
    }
    return base64;
  }

}

/**
 * 判断两元素是否相交
 * @param objOne 元素1
 * @param objTwo 元素2
 */
export function isIntersect(objOne, objTwo) {
  let offsetOne = getOffset(objOne);
  let offsetTwo = getOffset(objTwo);
  let x1 = offsetOne.left;
  let y1 = offsetOne.top;
  let x2 = x1 + objOne.getBoundingClientRect().width;
  let y2 = y1 + objOne.getBoundingClientRect().height;

  let x3 = offsetTwo.left;
  let y3 = offsetTwo.top;
  let x4 = x3 + objTwo.getBoundingClientRect().width;
  let y4 = y3 + objTwo.getBoundingClientRect().height;

  let zx = Math.abs(x1 + x2 - x3 - x4);
  let x = Math.abs(x1 - x2) + Math.abs(x3 - x4);
  let zy = Math.abs(y1 + y2 - y3 - y4);
  let y = Math.abs(y1 - y2) + Math.abs(y3 - y4);
  return (zx <= x && zy <= y);
}
//js方式实现jq的offset
function getOffset(Node, offset) {
  if (!offset) {
      offset = {};
      offset.top = 0;
      offset.left = 0;
  }

  if (Node == document.body) {//当该节点为body节点时，结束递归
      return offset;
  }

  offset.top += Node.offsetTop;
  offset.left += Node.offsetLeft;

  return getOffset(Node.parentNode, offset);//向上累加offset里的值
}